<template>
  <div class="detail-container">
    <el-card class="detail-card">
      <template #header>
        <div class="card-header">
          <span>工序详情</span>
          <el-button type="primary" @click="goBack">返回</el-button>
        </div>
      </template>
      
      <div v-loading="loading" class="detail-content">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="工序ID">{{ processDetail.id }}</el-descriptions-item>
          <el-descriptions-item label="工序编码">{{ processDetail.processCode }}</el-descriptions-item>
          <el-descriptions-item label="工序名称">{{ processDetail.processName }}</el-descriptions-item>
          <el-descriptions-item label="工单ID">{{ processDetail.workOrderId }}</el-descriptions-item>
          <el-descriptions-item label="工艺路线步骤ID">{{ processDetail.routeStepId }}</el-descriptions-item>
          <el-descriptions-item label="工作站ID">{{ processDetail.workstationId }}</el-descriptions-item>
          <el-descriptions-item label="设备ID">{{ processDetail.equipmentId }}</el-descriptions-item>
          <el-descriptions-item label="工序状态">
            <el-tag :type="getStatusType(processDetail.status)">{{ getStatusText(processDetail.status) }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="创建人">{{ processDetail.createdBy }}</el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ formatTime(processDetail.createdTime) }}</el-descriptions-item>
          <el-descriptions-item label="更新人">{{ processDetail.updatedBy }}</el-descriptions-item>
          <el-descriptions-item label="更新时间">{{ formatTime(processDetail.updatedTime) }}</el-descriptions-item>
        </el-descriptions>
      </div>
    </el-card>

    <!-- 操作按钮区域 -->
    <el-card class="operation-card" v-if="processDetail.id">
      <template #header>
        <span>工序操作</span>
      </template>
      
      <div class="operation-buttons">
        <el-button v-if="processDetail.status === 'initialized'" type="success" @click="handleAssign">分配工序</el-button>
        <el-button v-if="processDetail.status === 'assigned'" type="warning" @click="handleStart">开始工序</el-button>
        <el-button v-if="processDetail.status === 'running'" type="warning" @click="handlePause">暂停工序</el-button>
        <el-button v-if="processDetail.status === 'paused'" type="success" @click="handleResume">恢复工序</el-button>
        <el-button v-if="processDetail.status === 'running'" type="info" @click="handleHold">挂起工序</el-button>
        <el-button v-if="processDetail.status === 'hold'" type="success" @click="handleRelease">解除挂起</el-button>
        <el-button v-if="processDetail.status === 'running'" type="success" @click="handleComplete">完成工序</el-button>
        <el-button v-if="['running', 'paused'].includes(processDetail.status)" type="warning" @click="handleRework">工序返工</el-button>
        <el-button v-if="processDetail.status === 'running'" type="primary" @click="handleQualityCheck">质量检测</el-button>
        <el-button v-if="processDetail.status === 'running'" type="primary" @click="handleRecordMeasurement">记录测量</el-button>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts" name="ProcessDetail">
import { ref, onMounted } from "vue";
import { useRoute, useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import { 
  getProcessById,
  assignProcess,
  startProcess,
  pauseProcess,
  resumeProcess,
  completeProcess,
  holdProcess,
  releaseProcess,
  reworkProcess,
  checkProcessQuality,
  recordProcessMeasurement,
  type Process
} from "@/api/modules/process";

const route = useRoute();
const router = useRouter();
const loading = ref(false);
const processDetail = ref<Process.ProcessListItem>({} as Process.ProcessListItem);

// 获取状态类型
const getStatusType = (status: string) => {
  const statusMap: Record<string, string> = {
    'initialized': 'info',
    'assigned': 'warning',
    'running': 'primary',
    'paused': 'warning',
    'completed': 'success',
    'error': 'danger',
    'cancelled': 'info',
    'stopped': 'warning',
    'hold': 'danger',
    'scrapped': 'danger'
  };
  return statusMap[status] || 'info';
};

// 获取状态文本
const getStatusText = (status: string) => {
  const statusMap: Record<string, string> = {
    'initialized': '初始化',
    'assigned': '已分配',
    'running': '运行中',
    'paused': '已暂停',
    'completed': '已完成',
    'error': '异常',
    'cancelled': '已取消',
    'stopped': '已停止',
    'hold': '已挂起',
    'scrapped': '已报废'
  };
  return statusMap[status] || status;
};

// 格式化时间
const formatTime = (time: string | number[] | Date | undefined) => {
  if (!time) return '-';
  if (Array.isArray(time)) {
    // 处理 LocalDateTime 数组格式 [year, month, day, hour, minute, second]
    const [year, month, day, hour, minute, second] = time;
    return `${year}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')} ${String(hour).padStart(2, '0')}:${String(minute).padStart(2, '0')}:${String(second).padStart(2, '0')}`;
  }
  return new Date(time).toLocaleString();
};

// 获取工序详情
const getProcessDetail = async () => {
  const processId = route.params.id as string;
  if (!processId) return;
  
  loading.value = true;
  try {
    const res = await getProcessById(processId);
    processDetail.value = res.data;
  } catch (error) {
    console.error('获取工序详情失败:', error);
    ElMessage.error('获取工序详情失败');
  } finally {
    loading.value = false;
  }
};

// 返回列表
const goBack = () => {
  router.back();
};

// 分配工序
const handleAssign = async () => {
  try {
    const { value: formData } = await ElMessageBox.prompt(
      '请输入分配信息（格式：工位ID,设备ID）', 
      '分配工序', 
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPattern: /^\d+,\d+$/,
        inputErrorMessage: '请输入正确格式：工位ID,设备ID'
      }
    );
    
    const [workstationId, equipmentId] = formData.split(',');
    await assignProcess({
      processId: processDetail.value.id,
      workstationId,
      equipmentId
    });
    ElMessage.success('工序分配成功');
    getProcessDetail();
  } catch (error) {
    if (error !== 'cancel') {
      console.error('工序分配失败:', error);
      ElMessage.error('工序分配失败');
    }
  }
};

// 开始工序
const handleStart = async () => {
  try {
    const { value: formData } = await ElMessageBox.prompt(
      '请输入开始信息（格式：工单ID,设备ID,操作人ID）', 
      '开始工序', 
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPattern: /^.+,.+,.+$/,
        inputErrorMessage: '请输入正确格式：工单ID,设备ID,操作人ID'
      }
    );
    
    const [workOrderId, equipmentId, operatorId] = formData.split(',');
    await startProcess({
      processId: processDetail.value.id,
      workOrderId,
      equipmentId,
      operatorId
    });
    ElMessage.success('工序开始成功');
    getProcessDetail();
  } catch (error) {
    if (error !== 'cancel') {
      console.error('工序开始失败:', error);
      ElMessage.error('工序开始失败');
    }
  }
};

// 暂停工序
const handlePause = async () => {
  try {
    const { value: reason } = await ElMessageBox.prompt('请输入暂停原因', '暂停工序', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      inputPattern: /.+/,
      inputErrorMessage: '暂停原因不能为空'
    });
    
    await pauseProcess({
      processId: processDetail.value.id,
      operatorId: 'current_user',
      reason
    });
    ElMessage.success('工序暂停成功');
    getProcessDetail();
  } catch (error) {
    if (error !== 'cancel') {
      console.error('工序暂停失败:', error);
      ElMessage.error('工序暂停失败');
    }
  }
};

// 恢复工序
const handleResume = async () => {
  try {
    await resumeProcess({
      processId: processDetail.value.id,
      operatorId: 'current_user'
    });
    ElMessage.success('工序恢复成功');
    getProcessDetail();
  } catch (error) {
    console.error('工序恢复失败:', error);
    ElMessage.error('工序恢复失败');
  }
};

// 挂起工序
const handleHold = async () => {
  try {
    const { value: reason } = await ElMessageBox.prompt('请输入挂起原因', '挂起工序', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      inputPattern: /.+/,
      inputErrorMessage: '挂起原因不能为空'
    });
    
    await holdProcess({
      processId: processDetail.value.id,
      operatorId: 'current_user',
      reason
    });
    ElMessage.success('工序挂起成功');
    getProcessDetail();
  } catch (error) {
    if (error !== 'cancel') {
      console.error('工序挂起失败:', error);
      ElMessage.error('工序挂起失败');
    }
  }
};

// 解除挂起
const handleRelease = async () => {
  try {
    await releaseProcess({
      processId: processDetail.value.id,
      operatorId: 'current_user'
    });
    ElMessage.success('工序解挂成功');
    getProcessDetail();
  } catch (error) {
    console.error('工序解挂失败:', error);
    ElMessage.error('工序解挂失败');
  }
};

// 完成工序
const handleComplete = async () => {
  try {
    await completeProcess({
      processId: processDetail.value.id,
      operatorId: 'current_user'
    });
    ElMessage.success('工序完成成功');
    getProcessDetail();
  } catch (error) {
    console.error('工序完成失败:', error);
    ElMessage.error('工序完成失败');
  }
};

// 工序返工
const handleRework = async () => {
  try {
    const { value: reason } = await ElMessageBox.prompt('请输入返工原因', '工序返工', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      inputPattern: /.+/,
      inputErrorMessage: '返工原因不能为空'
    });
    
    await reworkProcess({
      processId: processDetail.value.id,
      operatorId: 'current_user',
      reason
    });
    ElMessage.success('工序返工成功');
    getProcessDetail();
  } catch (error) {
    if (error !== 'cancel') {
      console.error('工序返工失败:', error);
      ElMessage.error('工序返工失败');
    }
  }
};

// 质量检测
const handleQualityCheck = async () => {
  try {
    const { value: result } = await ElMessageBox.prompt('请输入质量检测结果', '质量检测', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      inputPattern: /.+/,
      inputErrorMessage: '检测结果不能为空'
    });
    
    await checkProcessQuality({
      processId: processDetail.value.id,
      operatorId: 'current_user',
      qualityResult: result
    });
    ElMessage.success('质量检测记录成功');
    getProcessDetail();
  } catch (error) {
    if (error !== 'cancel') {
      console.error('质量检测失败:', error);
      ElMessage.error('质量检测失败');
    }
  }
};

// 记录测量参数
const handleRecordMeasurement = async () => {
  try {
    const { value: measurements } = await ElMessageBox.prompt(
      '请输入测量参数（JSON格式）', 
      '记录测量参数', 
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPattern: /.+/,
        inputErrorMessage: '测量参数不能为空'
      }
    );
    
    let parsedMeasurements;
    try {
      parsedMeasurements = JSON.parse(measurements);
    } catch {
      ElMessage.error('请输入有效的JSON格式');
      return;
    }
    
    await recordProcessMeasurement({
      processId: processDetail.value.id,
      operatorId: 'current_user',
      measurements: parsedMeasurements
    });
    ElMessage.success('测量参数记录成功');
    getProcessDetail();
  } catch (error) {
    if (error !== 'cancel') {
      console.error('记录测量参数失败:', error);
      ElMessage.error('记录测量参数失败');
    }
  }
};

onMounted(() => {
  getProcessDetail();
});
</script>

<style scoped>
.detail-container {
  padding: 20px;
}

.detail-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.detail-content {
  min-height: 200px;
}

.operation-card {
  margin-top: 20px;
}

.operation-buttons {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.operation-buttons .el-button {
  margin: 0;
}
</style>